package chat.keepWind.handle;

import java.util.List;
import java.util.Map;

import chat.keepWind.bean.Config;
import chat.keepWind.bean.DataPackage;
import chat.keepWind.bean.User;
import chat.keepWind.util.ChatUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class OnlineInboundHandler extends SimpleChannelInboundHandler<DataPackage> {
	@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace(); 
        ctx.close();
    }

    @SuppressWarnings("unchecked")
	@Override
    public void channelRead0(ChannelHandlerContext ctx, final DataPackage data) throws Exception {
         
		//接到上线后的反馈，需带上昵称
		
		List<User> onlineUsers = (List<User>)ChatUtil.dataMap.get("onlineUsers");
		
		Config config = (Config)ChatUtil.dataMap.get("config");
		String nickName = data.getNickName();
		Map<String,User> userMap = config.getUserMap();
		User user = userMap.get(data.getFromIp());
		if(user!=null){
			nickName = user.getNickName();
		}
		
		User tmp = ChatUtil.isExsitsIp(onlineUsers, data.getFromIp());
		if(tmp==null){
			User u = new User();
			u.setIp(data.getFromIp());
			u.setNickName(nickName);
			onlineUsers.add(u);//加入用户
		}else{
			//是否昵称 有更新
			tmp.setNickName(nickName);
		}
		
	}
    
    
}
